from time import sleep
from selenium import webdriver
# from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
# from selenium.webdriver.common.touch_actions import TouchActions

# window.scrollTo(0,document.body.scrollHeight)


class Tools(object):
    """docstring for Tools"""

    def __init__(self, src):
        super(Tools, self).__init__()
        options = Options()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        # options.add_argument('--headless')
        # options.add_argument('blink-settings=imagesEnabled=false')
        # options.add_argument('--disable-gpu')
        
        # options.add_experimental_option(
        #     "mobileEmulation", {"deviceName": "iPad Pro"})
        self.driver = webdriver.Chrome(chrome_options=options)
        self.driver.set_window_size(400, 800)
        self.driver.set_network_conditions(
            offline=False, latency=3000,  # additional latency (ms)
            download_throughput=500 * 1024,  # maximal throughput
            upload_throughput=500 * 1024)  # maximal throughput
        self.driver.set_page_load_timeout(3)
        try:
            self.driver.get(src)
        except:
            print('')

    def script(self, src):
        jsruning = open(src, 'r')
        res = self.driver.execute_script(jsruning.read())
        jsruning.close()
        return res

    def down(self):
        self.driver.close()

    def get_xhr_logs(self,chrome):
        log_xhr_array = []
        for typelog in chrome.log_types:
            perfs = chrome.get_log(typelog)
            for row in perfs:
                log_data = row
                message_ = log_data['message']
                try:
                    log_json = json.loads(message_)
                    log = log_json['message']
                    if log['method'] == 'Network.responseReceived':
                        # 去掉静态js、css等，仅保留xhr请求
                        type_ = log['params']['type']
                        if type_ == "XHR":
                            log_xhr_array.append(log)
                except:
                    pass
        return log_xhr_array
